package cn.lili.modules.order.order.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.order.order.entity.dos.RankingDistribution;
import cn.lili.modules.order.order.entity.dos.RankingGrowAwardConfig;
import cn.lili.modules.order.order.entity.dos.RankingGrowAwardStatus;
import cn.lili.modules.order.order.entity.dto.RankingDistributionDTO;
import cn.lili.modules.order.order.entity.vo.DistributionAndGrowAwardVO;
import cn.lili.modules.order.order.mapper.RankingGrowAwardStatusMapper;
import cn.lili.modules.order.order.service.IRankingDistributionService;
import cn.lili.modules.order.order.service.IRankingGrowAwardConfigService;
import cn.lili.modules.order.order.service.IRankingGrowAwardStatusService;
import cn.lili.modules.system.constants.DictConstant;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 成长奖励奖品领取明细 服务实现类
 * </p>
 *
 * @author zhushiqing
 * @since 2023-12-21
 */
@Service
@AllArgsConstructor(onConstructor_= @Lazy)
public class RankingGrowAwardStatusServiceImpl extends ServiceImpl<RankingGrowAwardStatusMapper, RankingGrowAwardStatus> implements IRankingGrowAwardStatusService {

    private IRankingDistributionService rankingDistributionService;
    private IRankingGrowAwardConfigService rankingGrowAwardConfigService;
    private IRankingDistributionService distributionService;
    private UserClient userClient;
    /**
     * 领取奖励记录列表
     *
     * @return 领取奖励记录列表
     */
    @Override
    public ResultMessage<Object> statusPage(RankingGrowAwardStatus rankingGrowAwardStatus, PageVO page) {
//        if (StringUtils.isEmpty(rankingGrowAwardStatus.getGrowAwardConfigId())) {
//            throw new ServiceException("活动id为空：growAwardConfigId");
//        }
        Page<RankingGrowAwardStatus> resultPage = super.page(PageUtil.initPage(page), this.createWrapper(rankingGrowAwardStatus));
        return ResultUtil.data(this.conversion(resultPage));
    }

    /**
     * 数据转换
     * @param resultPage 数据
     * @return 转换后的数据
     */
    private IPage<RankingGrowAwardStatus> conversion(Page<RankingGrowAwardStatus> resultPage) {
        if (CollectionUtil.isEmpty(resultPage.getRecords())) {
            return resultPage;
        }
        for (RankingGrowAwardStatus growAwardStatus : resultPage.getRecords()) {
            RankingDistribution distribution = distributionService.getById(growAwardStatus.getDistributionId());
            if (distribution == null || StringUtils.isEmpty(distribution.getId())) {
                continue;
            }
            growAwardStatus.setDistributionName(distribution.getMemberName());
            if (distribution.getRebateTotal() != null) {
                String rebateTotal = this.replaceDigits(String.valueOf(distribution.getRebateTotal()));
                growAwardStatus.setDistributionRebateTotal(rebateTotal);
            }
            User user = userClient.getById(distribution.getMemberId());
            if (user != null && StringUtils.isNotEmpty(user.getId())) {
                growAwardStatus.setUsername(user.getFyName());
                growAwardStatus.setUserImage(user.getFace());
            }
        }
        return resultPage;
    }

    /**
     * 将保留前面一位数据。其他非小数点或的数据变星号
     * @param input 输入值
     * @return 输出值
     */
    public String replaceDigits(String input) {
        StringBuilder output = new StringBuilder();

        boolean decimalFound = false;
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '.') {
                decimalFound = true;
                output.append(c);
            } else if (Character.isDigit(c)) {
                if (decimalFound) {
                    output.append(c);
                } else if (output.isEmpty()) {
                    output.append(c);
                } else {
                    output.append('*');
                }
            } else {
                output.append(c);
            }
        }
        return output.toString();
    }

    /**
     * 查询条件创建
     * @param rankingGrowAwardStatus 参数
     * @return 查询条件
     */
    private Wrapper<RankingGrowAwardStatus> createWrapper(RankingGrowAwardStatus rankingGrowAwardStatus) {
        LambdaQueryWrapper<RankingGrowAwardStatus> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(rankingGrowAwardStatus.getGrowAwardConfigId())) {
            queryWrapper.eq(RankingGrowAwardStatus::getGrowAwardConfigId, rankingGrowAwardStatus.getGrowAwardConfigId());
        }
        queryWrapper.eq(RankingGrowAwardStatus::getDeleteFlag, Boolean.FALSE);
        queryWrapper.ne(RankingGrowAwardStatus::getAwardStatus, DictConstant.AWARD_STATUS_0);
        queryWrapper.orderByDesc(RankingGrowAwardStatus::getCreateTime);
        return queryWrapper;
    }


    /**
     * 分页获取成长奖励列表
     * @param dto
     * @return
     */
    @Override
    public ResultMessage<Page<DistributionAndGrowAwardVO>> getRankingGrowAwardStatusList(RankingDistributionDTO dto) {
        if (null != dto.getAwardStatus() && dto.getAwardStatus() == -1) {
            dto.setAwardStatus(null);
        }
        //成长奖励列表
        Page<DistributionAndGrowAwardVO> pageDisvo = rankingDistributionService.selectDistributionPageListNew(dto);
        if (CollUtil.isNotEmpty(pageDisvo.getRecords())) {
            //查询未完成的数据(没有奖品的数据)
            if (null != dto.getGrowAwardId() && dto.getGrowAwardId().equals(0)) {
                return ResultUtil.data(pageDisvo);
            }
            List<String> distributionIds = pageDisvo.getRecords().stream().map(item -> item.getId()).collect(Collectors.toList());
            LambdaQueryWrapper<RankingGrowAwardStatus> query = new LambdaQueryWrapper<>();
            query.eq(RankingGrowAwardStatus::getDeleteFlag, Boolean.FALSE);
            query.in(RankingGrowAwardStatus::getDistributionId, distributionIds);
            Page<RankingGrowAwardStatus> page = baseMapper.selectPage(new Page<>(dto.getPageNumber(), dto.getPageSize()), query);
            if (CollUtil.isNotEmpty(page.getRecords())) {
                this.processGrowAwardsData(pageDisvo.getRecords(), page.getRecords());
            }
        }

        /*
        if (ObjectUtil.isNotNull(dto.getGrowAwardId()) && !dto.getGrowAwardId().equals(0)||ObjectUtil.isNotNull(dto.getAwardStatus())) {
            //完成状态: 完成状态,不传代表查全部 0,未完成 (已完成:则传 奖品id1, 奖品id2 奖品id3)
            //领奖状态 0,未领奖 1,(待发货)已领奖 2,已发货
            //先查奖励领取表
            LambdaQueryWrapper<RankingGrowAwardStatus>  query = new LambdaQueryWrapper<>();
            query.eq(RankingGrowAwardStatus::getDeleteFlag, Boolean.FALSE);
            //奖品配置id
            if(ObjectUtil.isNotNull(dto.getGrowAwardId()) && !dto.getGrowAwardId().equals(0)){
                query.eq(RankingGrowAwardStatus::getGrowAwardConfigId, dto.getGrowAwardId());
            }
            //领奖状态
            if(ObjectUtil.isNotNull(dto.getAwardStatus())){
                query.eq(RankingGrowAwardStatus::getAwardStatus, dto.getAwardStatus());
            }
            //领奖明细
            Page<RankingGrowAwardStatus> page = baseMapper.selectPage(new Page<>(dto.getPageNumber(), dto.getPageSize()), query);
            if (CollUtil.isNotEmpty(page.getRecords())) {
                List<String> distributionIds = page.getRecords().stream().map(item -> item.getDistributionId()).collect(Collectors.toList());
                dto.setDistributionIds(distributionIds);
                //查询分销信息
//                Page<Distribution> distributionPage = distributionClient.selectDistributionPageList(dto);
                Page<RankingDistribution> distributionPage = rankingDistributionService.selectDistributionPageList(dto);
                if(CollUtil.isNotEmpty(distributionPage.getRecords())){
                    pageResult.setTotal(distributionPage.getTotal());
                    pageResult.setRecords(this.processGrowAwardsData(distributionPage.getRecords(), page.getRecords()));
                }
            }
        }else{
            //先查分销表
            //分页获取(分销员)成长奖励数据
//            Page<Distribution> distributionPage = distributionClient.selectDistributionPageList(dto);
            Page<RankingDistribution> distributionPage = rankingDistributionService.selectDistributionPageList(dto);
            if (distributionPage.getTotal() > 0) {
                List<String> distributionIds = distributionPage.getRecords().stream().map(item -> item.getId()).collect(Collectors.toList());
                LambdaQueryWrapper<RankingGrowAwardStatus>  query = new LambdaQueryWrapper<>();
                query.eq(RankingGrowAwardStatus::getDeleteFlag, Boolean.FALSE);
                query.in(RankingGrowAwardStatus::getDistributionId, distributionIds);
                Page<RankingGrowAwardStatus> page = baseMapper.selectPage(new Page<>(dto.getPageNumber(), dto.getPageSize()), query);
                if(CollUtil.isNotEmpty(page.getRecords())){
                    pageResult.setTotal(distributionPage.getTotal());
                    pageResult.setRecords(this.processGrowAwardsData(distributionPage.getRecords(), page.getRecords()));
                }
            }
        }*/
        return ResultUtil.data(pageDisvo);
    }


    /**
     * 处理成长奖励数据
     * @param distrivos
     * @param growAwardStatusList
     * @return
     */
    private void processGrowAwardsData(List<DistributionAndGrowAwardVO> distrivos, List<RankingGrowAwardStatus> growAwardStatusList) {
        // 1,这里增加成长奖励配置查询,下面遍历赋值给里面的List
        List<RankingGrowAwardConfig> rankingGrowAwardConfigs = rankingGrowAwardConfigService.list();
        Map<String, String> awardConfigMap = new HashMap<>();
        // 2,这里把奖励list转成map
        //转map
        for (RankingGrowAwardConfig rankingGrowAwardConfig : rankingGrowAwardConfigs) {
            awardConfigMap.put(rankingGrowAwardConfig.getId().toString(), rankingGrowAwardConfig.getGrowAwardName());
        }
        //合并奖品数据
        for (DistributionAndGrowAwardVO vo : distrivos) {
            for (RankingGrowAwardStatus rankingGrowAwardStatus : growAwardStatusList) {
                if (vo.getId().equals(rankingGrowAwardStatus.getDistributionId())) {
                    vo.getRankGrowAwards().add(rankingGrowAwardStatus);
                }
                // 3，从map获取值赋值奖品名称
                rankingGrowAwardStatus.setGrowAwardConfigName(awardConfigMap.get(rankingGrowAwardStatus.getGrowAwardConfigId()));
            }
        }
    }

    /**
     * 给成长奖励奖品填写物流信息
     * @param growAwardStatus
     * @return
     */
    @Override
    public ResultMessage<Object> addExpressNoToGrowAward(RankingGrowAwardStatus growAwardStatus) {
        //参数检查
        this.checkAddExpressionParam(growAwardStatus);
        RankingGrowAwardStatus domainData = baseMapper.selectById(growAwardStatus.getId());
        if (null == domainData || domainData.getDeleteFlag()) {
            throw new ServiceException("未找到该奖品记录");
        }
        domainData.setExpressNo(growAwardStatus.getExpressNo());
        domainData.setExpressName(growAwardStatus.getExpressName());
        domainData.setAwardStatus(2);
        if (baseMapper.updateById(domainData) > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error(400, "填写失败");
    }

    /**
     * 判空检查
     * @param domain
     */
    private void checkAddExpressionParam(RankingGrowAwardStatus domain) {
        if (null == domain || null == domain.getId()) {
            throw new ServiceException("缺少核心参数");
        }
        if (StringUtils.isEmpty(domain.getExpressName())) {
            throw new ServiceException("物流公司未填写");
        }
        if (StringUtils.isEmpty(domain.getExpressNo())) {
            throw new ServiceException("物流单号未填写");
        }
    }

    @Override
    public Long countUser() {
        return baseMapper.countUser();
    }
}
